package com.zbkj.crmeb.merchant.admin.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.exception.ExceptionCodeEnum;
import com.github.pagehelper.PageInfo;
import com.utils.ExcelUtil;
import com.utils.OSSUtil;
import com.utils.PriceUtil;
import com.utils.ProductConvertUtil;
import com.zbkj.crmeb.chant.request.PickingProductsRequest;
import com.zbkj.crmeb.chant.response.PickingProductResponse;
import com.zbkj.crmeb.chant.service.ChannelPickingService;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.export.service.ExcelService;
import com.zbkj.crmeb.export.vo.*;
import com.zbkj.crmeb.merchant.admin.service.MerExcelService;
import com.zbkj.crmeb.merchant.admin.service.MerStoreOrderService;
import com.zbkj.crmeb.merchant.admin.service.MerStoreProductService;
import com.zbkj.crmeb.store.dao.StoreProductDao;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.model.StoreProductUpload;
import com.zbkj.crmeb.store.model.Supplier;
import com.zbkj.crmeb.store.request.StoreOrderSearchRequest;
import com.zbkj.crmeb.store.request.StoreProductSearchRequest;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.service.StoreProductUploadService;
import com.zbkj.crmeb.store.service.SupplierService;
import com.zbkj.crmeb.system.service.SystemConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * 商品表 前端控制器
 */
@Slf4j
@Controller
@RequestMapping("api/admin/mer/export/excel")
@Api(tags = "导出 -- Excel")
public class MerExcelController extends AdminBaseController {
    @Autowired
    PriceUtil priceUtil;
    @Autowired
    private MerExcelService excelService;
    @Autowired
    SystemConfigService systemConfigService;
    @Autowired
    private MerStoreProductService storeProductService;
    @Autowired
    private MerStoreOrderService merStoreOrderService;
    @Autowired
    private StoreProductService productService;
    @Autowired
    private ExcelService aexcelService;
    @Autowired
    private ChannelPickingService channelPickingService;
    @Autowired
    private MerExcelService merExcelService;
    @Autowired
    private StoreProductUploadService storeProductUploadService;
    @Autowired
    private SupplierService supplierService;


    AtomicInteger atom = new AtomicInteger(0);
    final int max = 10;
    /**
     * 商品导出
     * @param request 搜索条件
     * @author Mr.Zhang
     * @since 2020-05-06
     */
    @ApiOperation(value = "云仓商品")
    @RequestMapping(value = "/product", method = RequestMethod.GET)
    public void export(@Validated StoreProductSearchRequest request, HttpServletResponse response, HttpServletRequest servletRequest){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                //云仓商品
                List<Integer> isNotEurope = Arrays.asList(ProductTypeEnum.INSIDE.getCode());
                request.setIsNotEurope(isNotEurope);
                List<ProductExcelVo> list = storeProductService.getExportList(request, pageParamRequest,getMerId(servletRequest));
                excelService.parseList(list);
                //sheet名称
                ExcelUtil.setSheetName("store");
                //文件名称前缀
                ExcelUtil.setFileName("产品导出");
                ExcelUtil.writeExcel(response, list, ProductExcelVo.class);
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    @ApiOperation(value = "自建商品")
    @RequestMapping(value = "/inside/product", method = RequestMethod.GET)
    public void exportInsideProductList(@Validated StoreProductSearchRequest request, HttpServletResponse response, HttpServletRequest servletRequest){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                //自建商品
                request.setIsEurope(ProductTypeEnum.INSIDE.getCode());
                request.setMerchantId(getMerId(servletRequest));
                //List<ProductExcelVo> list = storeProductService.getExportList(request, pageParamRequest,getMerId(servletRequest));
                List<ProductExcelVo> list = productService.getExprotList(request, pageParamRequest);
                aexcelService.parseList(list);
                List<StoreProductExcelVo> storeProductExcelVoList = Convert.toList(StoreProductExcelVo.class,list);
                //sheet名称
                ExcelUtil.setSheetName("store");
                //文件名称前缀
                ExcelUtil.setFileName("产品导出");
                ExcelUtil.writeExcelByIsImg(response, storeProductExcelVoList, StoreProductExcelVo.class,request.getIsImg());
            }
        }finally {
            atom.decrementAndGet();
        }
    }



    /**
     * 订单导出
     * @param request 搜索条件
     */
    @ApiOperation(value = "订单")
    @RequestMapping(value = "/storeOrder", method = RequestMethod.GET)
    public void storeOrderexport(@Validated StoreOrderSearchRequest request, HttpServletRequest servletRequest, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                request.setMerId(getMerId(servletRequest));
                List<MerStoreOrderExcelVo> productExcelVoList = merStoreOrderService.getExportList(request, pageParamRequest);
                //sheet名称
                ExcelUtil.setSheetName("订单信息表");
                //文件名称前缀
                ExcelUtil.setFileName("订单导出");
                ExcelUtil.writeExcelByIsImg(response, productExcelVoList, MerStoreOrderExcelVo.class,request.getIsImg());
//                ExcelUtil.writeExcel(response, productExcelVoList, MerStoreOrderExcelVo.class);
            }
        }finally {
            atom.decrementAndGet();
        }
    }


//
//
//    /**
//     * 分页显示商品表, 配合swagger使用
//     * @param request 搜索条件
//     * @author Mr.Zhang
//     * @since 2020-05-27
//     */
//    @ApiOperation(value = "分页列表")
//    @RequestMapping(value = "/products", method = RequestMethod.GET)
//    public void exportList(@Validated StoreProductSearchRequest request, HttpServletResponse response){
//        PageParamRequest pageParamRequest = new PageParamRequest();
//        pageParamRequest.setPage(Constants.DEFAULT_PAGE);
//        // 一次最多导出1000
//        pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
//        PageInfo<StoreProductResponse> pageInfo = storeProductService.getList(request, pageParamRequest);
//
//        List<StoreProductResponse> list = calcPrice(pageInfo.getList());
//        pageInfo.setList(list);
//        List<ProductExcelVo> productExcelVoList = excelService.convertList(list);
//        ExcelUtil.setSheetName("store");
//        ExcelUtil.setFileName("产品导出");
////        ExcelUtil.writeExcel(response,productExcelVoList,ProductExcelVo.class);
//        String fileName = ExcelUtil.writeExcelFile(productExcelVoList, ProductExcelVo.class);
//    }

    private List<StoreProductResponse> calcPrice(List<StoreProductResponse> pList){
        if(CollectionUtils.isNotEmpty(pList)){
            pList.forEach(p->{
                p.setOtPrice(priceUtil.eur2RmbStatic(p.getOtPrice(), p.getExchangeRate()));
//                if(StockAreaTempEnum.EUR.getTempId().equals(p.getTempId())){
//                    p.setCost(priceUtil.eur2Rmb(p.getCost()));
//                }else{
                    p.setCost(priceUtil.hk2Rmb(p.getCost()));
//                }
                if(CollectionUtils.isNotEmpty(p.getAttrValue())){
                    p.getAttrValue().forEach(attrVal -> {
//                        if(StockAreaTempEnum.EUR.getTempId().equals(p.getTempId())){
//                            attrVal.setCost(priceUtil.eur2Rmb(attrVal.getCost()));
//                        }else{
                            attrVal.setCost(priceUtil.hk2Rmb(attrVal.getCost()));
//                        }
                        attrVal.setOtPrice(priceUtil.eur2RmbStatic(attrVal.getOtPrice(), p.getExchangeRate()));
                    });
                    p.setAttrValue(p.getAttrValue().stream().filter(e->e.getStock()>0).collect(Collectors.toList()));
                }
                // 未设置运费，发货地是海外的时候 按售价百分比计算运费算运费
                if(StockAreaTempEnum.getByTempId(p.getTempId()).equals(StockAreaTempEnum.EUR)){
                    // 收货地是国内 , 计算运费
                    String postRate = StringUtils.defaultString(systemConfigService.getValueByKey(Constants.SYSTEM_CONFIG_POSTAGE_RATE),Constants.DEFAULT_POSTAGE_RATE);
                    BigDecimal postage = p.getPostage().add(p.getPrice().multiply(new BigDecimal(postRate).movePointLeft(2)).setScale(2,BigDecimal.ROUND_UP));
                    p.setPostage(postage);
                }
            });
        }
        return pList;
    }

    /**
     * 商户流水列表导出
     * @param merId
     * @param type
     * @param request
     * @param response
     */
    @ApiOperation(value = "商户流水列表导出")
    @RequestMapping(value = "/merFlowExport", method = RequestMethod.GET)
    public void merFlowExport(@ApiParam(value="商户id ", required = true)Integer merId, @ApiParam(value="类型:1 可用余额;2 可提现余额;3 已冻结金额", required = true)Integer type, PageParamRequest request, HttpServletRequest servletRequest, HttpServletResponse response){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                request.setPage(Constants.DEFAULT_PAGE);
                request.setLimit(Constants.EXPORT_MAX_LIMIT);
                List<MerFlowExcelVo> merFlowList = excelService.getMerFlowList(getMerId(servletRequest),type,request);
                //sheet名称
                ExcelUtil.setSheetName("商户流水信息");
                //文件名称前缀
                ExcelUtil.setFileName("商户流水");
                ExcelUtil.writeExcel(response, merFlowList, MerFlowExcelVo.class);
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    @ApiOperation(value = "批采单商品导出")
    @RequestMapping(value = "/picking/product", method = RequestMethod.GET)
    public void pickingExport(@Validated PickingProductsRequest request, HttpServletResponse response, HttpServletRequest servletRequest){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                request.setPage(Constants.DEFAULT_PAGE);
                request.setLimit(BooleanUtils.isTrue(request.getIsImg()) ? Constants.IMG_EXPORT_MAX_LIMIT : Constants.EXPORT_MAX_LIMIT);
                request.setMerId(getMerId(servletRequest));
                List<PickingProductResponse> responseList = channelPickingService.getProducts(request).getList();
                List<PickingProductExcelVo> list  = excelService.parsePickingVoList(responseList);
                //sheet名称
                ExcelUtil.setSheetName("picking");
                //文件名称前缀
                ExcelUtil.setFileName("批采单商品导出");
                ExcelUtil.writeExcelByIsImg(response, list, PickingProductExcelVo.class,request.getIsImg());
            }
        }finally {
            atom.decrementAndGet();
        }
    }

    @ApiOperation(value = "员工档案模板")
    @RequestMapping(value = "/download/template/employee", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<String> downloadEmployeeTemplate(){
        return CommonResult.success("https://italytao.oss-cn-shanghai.aliyuncs.com/product-warehouse-excel/template/staff-template.xlsx", ExceptionCodeEnum.SUCCESS.getMessage());
    }

    @ApiOperation(value = "批量导入员工")
    @RequestMapping(value = "/upload/employee", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> uploadExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        return CommonResult.success(merExcelService.uploadExcel(file, getMerId(request)));
    }

    @ApiOperation(value = "商户excel上传商品")
    @RequestMapping(value = "/upload/product", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> uploadExcelProduct(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        try {
            Supplier supplier = supplierService.getSupplierBarcode(getMerId(request));
            if(null == supplier){
                return CommonResult.failed("请给商户创建供应商后再添加商品!");
            }
            if(StringUtils.isBlank(file.getOriginalFilename())){
                throw new CrmebException("文件名不能为空");
            }
            String excelType = OSSUtil.getExcelType(FilenameUtils.getExtension("." + file.getOriginalFilename()));
            if (StringUtils.isEmpty(excelType)){
                throw new CrmebException("文件格式不合法，必须为csv,xls,xlsx");
            }
            long millis = System.currentTimeMillis();
            InputStream inputStream = file.getInputStream();
            List<UploadSupplierProductExcelVo> list = ExcelUtil.importExcel(inputStream,UploadSupplierProductExcelVo.class);
            StoreProductUpload storeProductUpload = merExcelService.importProductList(list,getMerId(request));
            String fileName = file.getOriginalFilename();
            if(fileName.contains("-")){
                fileName = fileName.substring(fileName.lastIndexOf("-")+1);
            }
            String url = OSSUtil.uploadLocalExcel(Constants.UPLOAD_EXCEL_FILE_WAREHOUSE_DIR, file, millis+"-" + fileName);
            storeProductUpload.setTime(System.currentTimeMillis()-millis);
            storeProductUpload.setUrl(url);
            storeProductUpload.setResult(StringUtils.isBlank(url) ? 0 : 1);
            storeProductUploadService.updateById(storeProductUpload);
            return CommonResult.success(storeProductUpload.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            throw new CrmebException(e.getMessage());
        }
    }

    @ApiOperation(value = "商品模板下载")
    @RequestMapping(value = "/download/template/product", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<String> downloadProductTemplate() {
        return CommonResult.success("https://italytao.oss-cn-shanghai.aliyuncs.com/product-warehouse-excel/template/product_import_template.xlsx", ExceptionCodeEnum.SUCCESS.getMessage());
    }

    // 导出用户购物车添加商品数据
    @GetMapping("/cart/product/{uid}")
    @ApiOperation(value = "导出指定用户购物车商品数据")
    public void getStoreCartProductByUid(@PathVariable Integer uid, HttpServletResponse response) {
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                List<ProductExcelVo> list = storeProductService.getStoreCartProductByUid(uid);
                aexcelService.parseList(list);
                List<StoreAdminProductExcelVo1> storeAdminProductExcelVoList = Convert.toList(StoreAdminProductExcelVo1.class,list);
                //sheet名称
                ExcelUtil.setSheetName("store");
                //文件名称前缀
                ExcelUtil.setFileName("产品导出");
                ExcelUtil.writeExcelByIsImg(response, storeAdminProductExcelVoList, StoreAdminProductExcelVo1.class, true);
            }
        }finally {
            atom.decrementAndGet();
        }
    }

}



